<template>
  <view class="firework" :style="{ backgroundColor: bgColor }" v-if="!isDestroy">
    <canvas class="firework__canvas" :canvas-id="canvasId" :id="canvasId" type="2d"></canvas>
    <view v-show="showTitle" class="firework__title">
      <span :style="{ color: titleColor, transform: 'translateX(0px)', opacity: 1 }">
        {{ title }}
      </span>
    </view>
  </view>
</template>
<script lang="ts">
  // @ts-nocheck
  import { getCurrentInstance, watch, watchEffect, onUnmounted, defineComponent, ref } from './vue';
  import { useCanvas } from './useCanvas';
  import { Confetti } from './confetti';
  import { Options } from './type';
  export default defineComponent({
    name: 'Firework',
    props: {
      title: {
        type: String,
        default: () => '',
      },
      titleColor: {
        type: String,
        default: () => '#fff',
      },
      bgColor: {
        type: String,
        default: () => '#000',
      },
    },
    emits: ['done'],
    setup(props, { expose, emit }) {
      const app = getCurrentInstance();
      const canvasId = `firework-${app.uid}`;
      const canvas = useCanvas(`#${canvasId}`, { context: app.proxy });
      let isDestroy = ref(false);
      let confetti = null;
      const showTitle = ref(false);

      const play = (options: Options) => {
        confetti.play(options);
      };
      const done = () => emit('done');

      watch(
        canvas,
        (v) => {
          if (v) {
            confetti = new Confetti(canvas.value, { resize: true, done });
          }
        },
        { immediate: true },
      );

      watchEffect(() => {
        if (props.title != '') {
          setTimeout(() => {
            showTitle.value = true;
          }, 1000);
        } else {
          showTitle.value = false;
        }
      });

      onUnmounted(() => {
        isDestroy.value = true;
        confetti = null;
      });
      // #ifdef VUE3
      expose({
        play,
      });
      // #endif
      return {
        isDestroy,
        canvasId,
        showTitle,

        // #ifndef VUE3
        // 由于VUE2 是通过返回暴露方法，故使用返回
        play,
        // #endif
      };
    },
  });
</script>
<style lang="scss">
  .firework {
    width: 100%;
    height: 100%;
    &__canvas {
      width: 100%;
      height: 100%;
    }

    &__title {
      position: absolute;
      left: 0;
      right: 0;
      top: 40%;
      bottom: 0;
      text-align: center;
      background: transparent;
      width: 100%;

      font-size: 40rpx;
      font-weight: bold;
    }
  }
</style>
